package com.chy.blog_server.modular.map.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chy.blog_server.modular.map.config.GdConfing;
import com.chy.blog_server.modular.map.entity.MapDistrict;
import com.chy.blog_server.modular.map.entity.MapMerchantInfo;
import com.chy.blog_server.modular.map.mapper.MapDistrictMapper;
import com.chy.blog_server.modular.map.service.IMapDistrictService;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述：行政地区 service业务层
 * 作者：chenhuiyan
 * 时间：2025/03/19 12:03
 */
@Service
@Transactional(readOnly = true)
public class MapDistrictServiceImpl extends ServiceImpl<MapDistrictMapper, MapDistrict> implements IMapDistrictService {

    private static final Logger logger = LoggerFactory.getLogger(MapMerchantInfoServiceImpl.class);

    /**
     * 查询列表-分页
     * @param params
     * @return
     */
    public List<Map<String, Object>> listPage(Map<String, Object> params){
        return baseMapper.listPage(params);
    }

    /**
     * 查询列表-不分页
     * @param params
     * @return
     */
    public List<Map<String, Object>> listAll(Map<String, Object> params){
        return baseMapper.listAll(params);
    }

    /**
     * 查询列表-实体-不分页
     * @param params
     * @return
     */
    public List<MapDistrict> listAllEntity(Map<String, Object> params){
        return baseMapper.listAllEntity(params);
    }

    /**
     * 查询省份列表
     * @return
     */
    public List<MapDistrict> provinceList(){
        return baseMapper.selectList(new QueryWrapper<MapDistrict>().eq("level", "province").orderByAsc("adcode"));
    }

    /**
     * 查询城市列表：并且级别为城市
     * @return
     */
    public List<MapDistrict> cityList(String provinceCode){
        return baseMapper.selectList(new QueryWrapper<MapDistrict>().eq("pa_adcode", provinceCode).eq("level", "city").orderByAsc("adcode"));
    }

    /**
     * 查询城市下级的区/县或者街道的坐标
     * @param provinceCode 省份编码
     * @param cityCode 城市编码
     * @return
     */
    public List<Map<String, String>> getDistrictStreetCenterList(String provinceCode, String cityCode){
        List<Map<String, String>> locationList = new ArrayList<>();
        List<MapDistrict> list = baseMapper.selectList(new QueryWrapper<MapDistrict>().eq("pa_adcode", cityCode).orderByAsc("adcode"));
        if(list.isEmpty()){
            //如果没有区/县或者街道，则查城市（暂时还不会出现这种情况，因为有城市的就存在区/县或者街道）
            list = baseMapper.selectList(new QueryWrapper<MapDistrict>().eq("adcode", cityCode));
            if(list.isEmpty()){
                //如果没有城市，则查省：例：台湾
                list = baseMapper.selectList(new QueryWrapper<MapDistrict>().eq("adcode", provinceCode));
            }
        }
        if(!list.isEmpty()){
            for (MapDistrict mapDistrict : list) {
                Map<String, String> map = new HashMap<>();
                map.put("name", mapDistrict.getName()); //名称
                map.put("center", mapDistrict.getCenter()); //坐标
                locationList.add(map);
            }
        }
        return locationList;
    }

    /**
     * 查询总数-不分页使用
     * @param params
     * @return
     */
    public int getCountAll(Map<String, Object> params){
        return baseMapper.getCountAll(params);
    }

    /**
     * 查询总数-分页使用
     * @param params
     * @return
     */
    public int getCount(Map<String, Object> params){
        return baseMapper.getCount(params);
    }

    /**
     * 生成行政地区
     * @return
     */
    @Transactional(readOnly = false)
    public void withUpdateDistrict(HttpServletRequest request) throws Exception {
        String url = GdConfing.buildGdDistrictRequestUrl();
        JsonNode root = GdConfing.sendApiRequest(url);
        if("0".equals(root.get("status").asText())){
            logger.info("高德API接口调用>>>>>>>>>生成高徳行政地区--发生错误：{}", root);
            throw new Exception(root.get("msg").asText());
        } else if("1".equals(root.get("count").asText())){
            List<MapDistrict> list = new ArrayList<>();
            JsonNode districts = root.get("districts"); //国
            if(districts != null && !"[]".equals(districts.toString())){
                JsonNode provinceNode = districts.get(0).get("districts"); //省
                provinceNode.forEach(node -> {
                    //生成省数据
                    MapDistrict pMapDistrict = new MapDistrict();
                    pMapDistrict.preInsert(request);
                    pMapDistrict.setName(node.get("name").asText()); //名称
                    pMapDistrict.setLongName(node.get("name").asText()); //省市县名称
                    pMapDistrict.setAdcode(node.get("adcode").asText()); //编码
                    pMapDistrict.setLevel(node.get("level").asText()); //级别：province省/直辖市,city市,district区/县
                    pMapDistrict.setCenter(node.get("center").asText()); //位置
                    list.add(pMapDistrict);

                    JsonNode cityNode= node.get("districts"); //城市
                    if(cityNode != null && !"[]".equals(cityNode.toString())){
                        cityNode.forEach(cnode -> {
                            //生成城市数据
                            MapDistrict cMapDistrict = new MapDistrict();
                            cMapDistrict.preInsert(request);
                            cMapDistrict.setName(cnode.get("name").asText()); //名称
                            cMapDistrict.setLongName(node.get("name").asText() + cnode.get("name").asText()); //省市县名称
                            cMapDistrict.setAdcode(cnode.get("adcode").asText()); //编码
                            cMapDistrict.setPaAdcode(node.get("adcode").asText()); //上级编码
                            cMapDistrict.setLevel(cnode.get("level").asText()); //级别：province省/直辖市,city市,district区/县
                            cMapDistrict.setCenter(cnode.get("center").asText()); //位置
                            list.add(cMapDistrict);

                            JsonNode areNode= cnode.get("districts"); //区/县
                            if(areNode != null && !"[]".equals(areNode.toString())){
                                areNode.forEach(anode -> {
                                    //生成区/县/街道数据
                                    MapDistrict aMapDistrict = new MapDistrict();
                                    aMapDistrict.preInsert(request);
                                    aMapDistrict.setName(anode.get("name").asText()); //名称
                                    aMapDistrict.setLongName(node.get("name").asText() + cnode.get("name").asText() + anode.get("name").asText()); //省市县名称
                                    aMapDistrict.setAdcode(anode.get("adcode").asText()); //编码
                                    aMapDistrict.setPaAdcode(cnode.get("adcode").asText()); //上级编码
                                    aMapDistrict.setLevel(anode.get("level").asText()); //级别：province省/直辖市,city市,district区/县,street街道
                                    aMapDistrict.setCenter(anode.get("center").asText()); //位置
                                    list.add(aMapDistrict);
                                });
                            }
                        });
                    }
                });
                //删除全部旧数据再新增
                if(!list.isEmpty()){
                    baseMapper.deleteAll();
                    List<MapDistrict> saveList = new ArrayList<>();
                    for (MapDistrict mapDistrict : list) {
                        saveList.add(mapDistrict);
                        if(saveList.size() == 800){
                            saveBatch(saveList);
                            saveList.clear();
                        }
                    }
                    if(!saveList.isEmpty()){
                        saveBatch(saveList);
                    }
                }
            }else{
                String error = "高德API接口调用>>>>>>>>生成高徳行政地区--发生错误";
                logger.info(error);
                throw new Exception(error);
            }
        }
    }

    /**
     * 彻底删除
     * @param id
     * @return
     */
    public int thoroughlyDelete(String id){
        return baseMapper.thoroughlyDelete(id);
    }

}
